<template>
  <div class="app-container">
    <!-- 返回按钮和项目名称 -->
    <div class="mb-6 flex justify-between items-center">
      <el-button type="primary" plain @click="goBack" icon="Back">返回成本消耗管理</el-button>
      <el-tag type="info" size="large" effect="plain">{{ projectInfo.proName || '加载中...' }}</el-tag>
    </div>

    <!-- 项目详情卡片 -->
    <ProjectDetail :project-info="projectInfo" :loading="projectLoading" />

    <!-- 成本统计卡片 -->
    <el-card class="mb-6 statistics-card">
      <template #header>
        <div class="statistics-header">
          <el-icon class="statistics-icon">
            <Money />
          </el-icon>
          <span class="statistics-title">项目成本消耗统计汇总</span>
        </div>
      </template>
      <div class="statistics-grid">
        <div class="stat-item">
          <div class="stat-label">人员成本总计</div>
          <div class="stat-value staff-cost">{{ formatAmount(totalStatistics.staffCost) }}元</div>
          <div class="stat-desc">项目人员投入成本</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">差旅成本总计</div>
          <div class="stat-value travel-cost">{{ formatAmount(totalStatistics.travelCost) }}元</div>
          <div class="stat-desc">出差交通住宿成本</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">办公成本总计</div>
          <div class="stat-value office-cost">{{ formatAmount(totalStatistics.officeCost) }}元</div>
          <div class="stat-desc">办公用品设备成本</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">总消耗成本</div>
          <div class="stat-value total-cost">{{ formatAmount(totalStatistics.totalCost) }}元</div>
          <div class="stat-desc">所有成本项目合计</div>
        </div>
      </div>
    </el-card>

    <!-- 成本消耗信息卡片 -->
    <el-card class="box-card cost-card mb-6" v-loading="loading">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="card-header-left">
            <span class="title">成本消耗信息</span>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="success" plain icon="Plus" @click="handleAdd" v-hasPermi="['project:consume:add']" size="default">
                  新增成本记录
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['project:consume:export']" size="default">
                  导出
                </el-button>
              </el-col>
            </el-row>
          </div>
          <div class="flex items-center" style="gap: 12px">
            <RefreshButton @refresh="handleQuery" />
          </div>
        </div>
      </template>

      <!-- 成本消耗信息表格 -->
      <div class="cost-container">
        <el-table :data="costList" border style="width: 100%" row-key="id" :row-class-name="tableRowClassName">
          <!-- 项目名称 -->
          <el-table-column label="项目名称" align="center" min-width="200" fixed="left" :show-overflow-tooltip="true">
            <template #default="scope">
              <span>{{ scope.row.proName || '-' }}</span>
            </template>
          </el-table-column>

          <!-- 项目执行总裁 -->
          <el-table-column label="项目执行总裁" align="center" min-width="150" fixed="left" :show-overflow-tooltip="true">
            <template #default="scope">
              <span>{{ scope.row.proPresidentsName || '-' }}</span>
            </template>
          </el-table-column>

          <!-- 项目负责人 -->
          <el-table-column label="项目负责人" align="center" min-width="150" fixed="left" :show-overflow-tooltip="true">
            <template #default="scope">
              <span>{{ scope.row.proLeadersName || '-' }}</span>
            </template>
          </el-table-column>

          <!-- 人员成本 -->
          <el-table-column label="人员成本" align="center" min-width="150">
            <template #default="scope">
              <MoneyInput v-if="scope.row.isEditing" v-model="scope.row.staffCost" placeholder="请输入人员成本（保留两位小数）"
                :min="0" @change="calculateTotalCost(scope.row)" />
              <span v-else-if="scope.row.staffCost">{{ formatAmount(scope.row.staffCost) }}元</span>
              <span v-else class="text-gray-400">0.00元</span>
            </template>
          </el-table-column>

          <!-- 差旅成本 -->
          <el-table-column label="差旅成本" align="center" min-width="150">
            <template #default="scope">
              <MoneyInput v-if="scope.row.isEditing" v-model="scope.row.travelCost" placeholder="请输入差旅成本（保留两位小数）"
                :min="0" @change="calculateTotalCost(scope.row)" />
              <span v-else-if="scope.row.travelCost">{{ formatAmount(scope.row.travelCost) }}元</span>
              <span v-else class="text-gray-400">0.00元</span>
            </template>
          </el-table-column>

          <!-- 办公成本 -->
          <el-table-column label="办公成本" align="center" min-width="150">
            <template #default="scope">
              <MoneyInput v-if="scope.row.isEditing" v-model="scope.row.officeCost" placeholder="请输入办公成本（保留两位小数）"
                :min="0" @change="calculateTotalCost(scope.row)" />
              <span v-else-if="scope.row.officeCost">{{ formatAmount(scope.row.officeCost) }}元</span>
              <span v-else class="text-gray-400">0.00元</span>
            </template>
          </el-table-column>

          <!-- A1成本 -->
          <el-table-column label="A1成本" align="center" min-width="150">
            <template #default="scope">
              <MoneyInput v-if="scope.row.isEditing" v-model="scope.row.a1Cost" placeholder="请输入A1成本（保留两位小数）" :min="0"
                @change="calculateTotalCost(scope.row)" />
              <span v-else-if="scope.row.a1Cost">{{ formatAmount(scope.row.a1Cost) }}元</span>
              <span v-else class="text-gray-400">0.00元</span>
            </template>
          </el-table-column>

          <!-- A2成本 -->
          <el-table-column label="A2成本" align="center" min-width="150">
            <template #default="scope">
              <MoneyInput v-if="scope.row.isEditing" v-model="scope.row.a2Cost" placeholder="请输入A2成本（保留两位小数）" :min="0"
                @change="calculateTotalCost(scope.row)" />
              <span v-else-if="scope.row.a2Cost">{{ formatAmount(scope.row.a2Cost) }}元</span>
              <span v-else class="text-gray-400">0.00元</span>
            </template>
          </el-table-column>

          <!-- 其他成本 -->
          <el-table-column label="其他成本" align="center" min-width="150">
            <template #default="scope">
              <MoneyInput v-if="scope.row.isEditing" v-model="scope.row.otherCost" placeholder="请输入其他成本（保留两位小数）"
                :min="0" @change="calculateTotalCost(scope.row)" />
              <span v-else-if="scope.row.otherCost">{{ formatAmount(scope.row.otherCost) }}元</span>
              <span v-else class="text-gray-400">0.00元</span>
            </template>
          </el-table-column>

          <!-- 总成本 -->
          <el-table-column label="总成本" align="center" min-width="180">
            <template #default="scope">
              <span style="color: #f56c6c; font-weight: bold">{{ formatAmount(scope.row.totalCost) }}元</span>
            </template>
          </el-table-column>

          <!-- 创建时间 -->
          <el-table-column label="更新时间" align="center" prop="updateTime" min-width="150">
            <template #default="scope">
              {{ scope.row.updateTime ? parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') : '' }}
            </template>
          </el-table-column>

          <!-- 备注 -->
          <el-table-column label="备注" align="center" width="300">
            <template #default="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.remark" :rows="3" type="textarea"
                placeholder="请输入备注" />
              <el-tooltip v-else :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
                <span class="text-overflow">{{ scope.row.remark || '-' }}</span>
              </el-tooltip>
            </template>
          </el-table-column>

          <!-- 操作 -->
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="scope">
              <!-- 编辑模式下的操作按钮 -->
              <template v-if="scope.row.isEditing">
                <el-button size="small" type="primary" @click="saveCost(scope.row)" :loading="scope.row.saving"> 保存
                </el-button>
                <el-button size="small" type="danger" @click="cancelEdit(scope.row)" :disabled="scope.row.saving"> 取消
                </el-button>
              </template>
              <!-- 查看模式下的操作按钮 -->
              <template v-else>
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="editCost(scope.row)"
                    v-hasPermi="['project:consume:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="danger" icon="Delete" @click="deleteCost(scope.row)"
                    v-hasPermi="['project:consume:remove']"></el-button>
                </el-tooltip>
              </template>
            </template>
          </el-table-column>

          <template #empty>
            <el-empty description="暂无成本消耗数据" />
          </template>
        </el-table>

        <!-- 底部信息组件 -->
        <ProjectBottomInfo :project-list="costList" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { getProDetail } from '@/api/project/init/proInfo';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';
import { listProCostConsume, addProCostConsume, updateProCostConsume, delProCostConsume } from '@/api/project/cost/consume';
import type { ProCostConsumeVO, ProCostConsumeForm } from '@/api/project/cost/consume/types';
import ProjectDetail from '@/views/project/components/ProjectDetail.vue';
import ProjectBottomInfo from '@/views/project/components/ProjectBottomInfo.vue';
import RefreshButton from '@/views/project/components/RefreshButton.vue';
import MoneyInput from '@/components/MoneyInput/index.vue';
import { formatAmount } from '@/components/NumberInput';

const route = useRoute();
const router = useRouter();

// 项目信息
const projectInfo = ref<Partial<ProInfoVO>>({});
const projectLoading = ref(false);

const { proxy } = getCurrentInstance() as any;

// 成本消耗列表
const costList = ref<ProCostConsumeVO[]>([]);

// 项目ID
const proId = ref<number>(Number(route.params.proId));

// 加载状态
const loading = ref(false);

// 统计数据
const totalStatistics = ref({
  staffCost: 0,
  travelCost: 0,
  officeCost: 0,
  a1Cost: 0,
  a2Cost: 0,
  otherCost: 0,
  totalCost: 0
});


/**
 * 刷新数据
 */
const handleQuery = () => {
  getCostList();
};

/**
 * 获取成本消耗列表数据
 */
const getCostList = async () => {
  try {
    loading.value = true;
    const res = await listProCostConsume(proId.value);
    costList.value = (res.data || []).map((item) => ({
      ...item,
      isEditing: false,
      saving: false,
      originalData: null
    }));
    // 计算统计数据
    calculateTotalStatistics();
  } catch (error) {
    console.error('获取成本消耗列表失败:', error);
  } finally {
    loading.value = false;
  }
};

/**
 * 获取项目信息
 * 根据路由参数中的项目ID获取详细信息
 */
const getProjectDetail = async () => {
  const proId = route.params.proId as string;
  if (!proId) {
    ElMessage.error('项目ID不能为空');
    return;
  }

  try {
    projectLoading.value = true;
    const res = await getProDetail(proId);
    projectInfo.value = res.data || {};
  } catch (error) {
    console.error('获取项目信息失败:', error);
    ElMessage.error('获取项目信息失败');
  } finally {
    projectLoading.value = false;
  }
};

/**
 * 安全转换金额数值
 */
const safeNumber = (value: any): number => Number(value) || 0;

/**
 * 计算单行总成本
 */
const calculateTotalCost = (row: any) => {
  const staffCost = safeNumber(row.staffCost);
  const travelCost = safeNumber(row.travelCost);
  const officeCost = safeNumber(row.officeCost);
  const a1Cost = safeNumber(row.a1Cost);
  const a2Cost = safeNumber(row.a2Cost);
  const otherCost = safeNumber(row.otherCost);

  row.totalCost = Number((staffCost + travelCost + officeCost + a1Cost + a2Cost + otherCost).toFixed(2));

  // 重新计算统计数据
  calculateTotalStatistics();
};

/**
 * 计算总统计数据
 */
const calculateTotalStatistics = () => {
  const totals = costList.value.reduce(
    (acc, item) => ({
      staffCost: acc.staffCost + safeNumber(item.staffCost),
      travelCost: acc.travelCost + safeNumber(item.travelCost),
      officeCost: acc.officeCost + safeNumber(item.officeCost),
      a1Cost: acc.a1Cost + safeNumber(item.a1Cost),
      a2Cost: acc.a2Cost + safeNumber(item.a2Cost),
      otherCost: acc.otherCost + safeNumber(item.otherCost),
      totalCost: acc.totalCost + safeNumber(item.totalCost)
    }),
    { staffCost: 0, travelCost: 0, officeCost: 0, a1Cost: 0, a2Cost: 0, otherCost: 0, totalCost: 0 }
  );
  totalStatistics.value = totals;
};

/**
 * 新增成本记录
 */
const handleAdd = () => {
  const newCost = {
    id: null,
    proId: proId.value,
    proName: projectInfo.value.proName || '',
    proPresidentsName: projectInfo.value.proPresidentsName || '',
    proLeadersName: projectInfo.value.proLeadersName || '',
    staffCost: 0,
    travelCost: 0,
    officeCost: 0,
    a1Cost: 0,
    a2Cost: 0,
    otherCost: 0,
    totalCost: 0,
    remark: '',
    isEditing: true,
    saving: false,
    originalData: null
  };
  costList.value.unshift(newCost);
};

/**
 * 编辑成本记录
 */
const editCost = (row: any) => {
  // 保存原始数据
  row.originalData = { ...row };
  row.isEditing = true;
};

/**
 * 取消编辑
 */
const cancelEdit = (row: any) => {
  if (row.originalData) {
    // 恢复原始数据
    Object.assign(row, row.originalData);
    row.originalData = null;
  } else {
    // 新增的记录，直接删除
    const index = costList.value.findIndex(item => item === row);
    if (index > -1) {
      costList.value.splice(index, 1);
    }
  }
  row.isEditing = false;
  // 重新计算统计数据
  calculateTotalStatistics();
};

/**
 * 保存成本记录
 */
const saveCost = async (row: any) => {
  try {
    row.saving = true;

    const formData: ProCostConsumeForm = {
      id: row.id,
      proId: row.proId,
      proName: row.proName,
      proPresidentsName: row.proPresidentsName,
      proLeadersName: row.proLeadersName,
      staffCost: row.staffCost,
      travelCost: row.travelCost,
      officeCost: row.officeCost,
      a1Cost: row.a1Cost,
      a2Cost: row.a2Cost,
      otherCost: row.otherCost,
      totalCost: row.totalCost,
      remark: row.remark
    };

    if (row.id) {
      // 更新
      await updateProCostConsume(formData);
      ElMessage.success('成本记录更新成功');
    } else {
      // 新增
      const res = await addProCostConsume(formData);
      row.id = res.data?.id || Date.now(); // 设置ID
      ElMessage.success('成本记录添加成功');
    }

    row.isEditing = false;
    row.originalData = null;

    // 刷新列表
    getCostList();
  } catch (error) {
    console.error('保存成本记录失败:', error);
    ElMessage.error('保存失败，请重试');
  } finally {
    row.saving = false;
  }
};

/**
 * 删除成本记录
 */
const deleteCost = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认删除该成本记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await delProCostConsume(row.id);
    ElMessage.success('删除成功');

    // 刷新列表
    getCostList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除成本记录失败:', error);
      ElMessage.error('删除失败，请重试');
    }
  }
};

/**
 * 导出数据
 */
const handleExport = () => {
  proxy.download(
    'pro/cost/consume/export',
    {
      proId: proId.value
    },
    `成本消耗_${new Date().getTime()}.xlsx`
  );
};

/**
 * 表格行样式
 */
const tableRowClassName = ({ row }: { row: any }) => {
  if (row.isEditing) {
    return 'editing-row';
  }
  return '';
};

/**
 * 返回上一页
 */
const goBack = () => {
  router.back();
};

// 页面初始化
onMounted(() => {
  getProjectDetail();
  getCostList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

/* 统计卡片样式 */
.statistics-card {
  background: linear-gradient(135deg, #f8faff 0%, #f0f7ff 100%);
  border: 1px solid #e1ecff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.08);
  border-radius: 8px;
}

.statistics-header {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--el-color-primary);
  font-weight: 600;
}

.statistics-icon {
  font-size: 20px;
  color: var(--el-color-primary);
}

.statistics-title {
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.statistics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 24px;
  padding: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 20px 16px;
  background: #fff;
  border-radius: 12px;
  border: 1px solid #e1ecff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.12);
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
  line-height: 1.2;
}

.stat-desc {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  line-height: 1.4;
}

.staff-cost {
  color: #10b981;
}

.travel-cost {
  color: #f59e0b;
}

.office-cost {
  color: var(--el-color-primary);
}

.total-cost {
  color: #f56c6c;
}

.cost-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

/* 卡片头部样式 - 参考split页面 */
.card-header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-header-left .title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-header-left .el-button {
  transition: all 0.2s ease;
}

.card-header-left .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.cost-container {
  position: relative;
  /* 增加底部空白 */
}

.text-overflow {
  display: inline-block;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

.text-gray-400 {
  color: #c0c4cc;
}

:deep(.editing-row) {
  background-color: #f0f9ff;
}

:deep(.el-table .editing-row td) {
  background-color: #f0f9ff !important;
}

:deep(.is-error .el-input__inner) {
  border-color: #f56c6c;
}

:deep(.el-input-number.is-error .el-input__inner) {
  border-color: #f56c6c;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 8px;
  }

  .card-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .card-header .left {
    flex-wrap: wrap;
    gap: 8px;
  }

  /* 统计卡片响应式 */
  .statistics-grid {
    grid-template-columns: 1fr;
    gap: 16px;
    padding: 16px 0;
  }

  .stat-item {
    padding: 16px 12px;
  }

  .stat-value {
    font-size: 20px;
  }

  .stat-label {
    font-size: 13px;
  }

  .stat-desc {
    font-size: 11px;
  }
}
</style>